package com.hyl.authdemo.service;

import com.hyl.authdemo.util.CodeUtil;
import com.hyl.authdemo.util.CommenCode;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2022/7/5 15:10
 **/
@Service("EmailService")
public class EmailServiceImpl implements EmailService {

	@Resource
	JavaMailSender javaMailSender;

	@Resource
	RedisService redisService;

	@Override
	public void send(String to) {
		try {
			SimpleMailMessage mailMessage = new SimpleMailMessage(); //纯文本
			mailMessage.setTo(to);
			mailMessage.setFrom("394022309@qq.com");
			mailMessage.setSubject("邮箱测试");

			String code = CodeUtil.getCode(4);
			Integer time = 30;//
			mailMessage.setText("验证码：" + code+",有效时间："+time);
			javaMailSender.send(mailMessage);

			//将验证码写入到Redis中
			String key = CommenCode.REGISTER_EMAIL + to;
			redisService.set(key, code,time);
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public boolean checkEmail(String to, String code)  {
		String key =  CommenCode.REGISTER_EMAIL +to;
		String redisCode = redisService.get(key);
		if(redisCode!=null && redisCode.equals(code)){
			//验证成功，删除缓存中的数据
			redisService.del(key);
			return true;
		}
		return false;
	}
}
